// 禁用上下拖动
var firstMove;
window.addEventListener('touchstart', function (e) {
  firstMove = true;
});
window.addEventListener('touchmove', function (e) {
  if (firstMove) {
    e.preventDefault();
    firstMove = false;
  }
});

function isWeixinBrowser() {
  var ua = navigator.userAgent.toLowerCase();
  return (/micromessenger/.test(ua));
}

let loadingQueue = new createjs.LoadQueue();
loadingQueue.installPlugin(createjs.Sound);
loadingQueue.on("complete", handleComplete, this);
// loadingQueue.loadFile({id: "bgSound", src: "./sound/bg.mp3"});
loadingQueue.loadManifest([
  {id: "loading", src: "./img/loading.png"}
]);

function handleComplete() {
  if (isWeixinBrowser()) {
    wx.config({
      debug: false,
      appId: '',
      timestamp: 1,
      nonceStr: '',
      signature: '',
      jsApiList: []
    });
    wx.ready(function () {
      wx.hideOptionMenu();
      loadingAssets();
    });
  } else {
    loadingAssets();
  }
}

function switchScene(from, to) {
  from.addClass('hide');
  to.removeClass('hide');
}

let loadingAssetsQueue;
let bgSound;
let loadingAssetsQueue2;

function loadingAssets() {
  t = new Date().getTime();
  loadingAssetsQueue = new createjs.LoadQueue();
  loadingAssetsQueue.installPlugin(createjs.Sound);
  createjs.CSSPlugin.install(createjs.Tween);
  loadingAssetsQueue.on("progress", handleProgress, this);
  loadingAssetsQueue.on("complete", loadingAssetsComplete, this);
  // bgSound = createjs.Sound.play("bgSound", {loop: -1, volume: 0.5});
  loadingAssetsQueue.loadManifest(assets);
}

function handleProgress(e) {
  $('#loadingProgress').text(Math.ceil(e.progress * 100) + '%');
}

function loadingAssetsComplete() {
  switchScene($('#stageLoading'), $('#stage2'));
  showScene2();
  // switchScene($('#stageLoading'), $('#stage6'));
  // showScene6();
}

function showScene2() {
  texts.map((item, index) => {
    let target = document.getElementById(item.id);
    Transform(target);
    target.translateY = -500;
    createjs.Tween.get(target).wait(index * 100).to({translateY: 0}, 300).call(() => {
      createjs.Sound.play("textDrop", {volume: 0.5});
      if (index === texts.length - 1) {
        setTimeout(() => {
          switchScene($('#stage2'), $('#stage3'));
          showScene3();
        }, 2000);
      }
    });
  });
}

function showScene3() {
  let container = document.getElementById('s3text');
  let crack = document.getElementById('s3crack');
  let fragment = new DocumentFragment;
  let texts = [];
  Transform(crack);

  function crackTween() {
    createjs.Sound.play("crack");
    createjs.Tween.get(crack)
        .set({opacity: 1}, crack.style)
        .wait(600)
        .to({
          scaleX: 2,
          scaleY: 2
        }, 600)
        .call(showScene4);
  }

  scene3text.map((item) => {
    let img = loadingAssetsQueue.getResult(item.id);
    let div = document.createElement('div');
    img.classList.add('img-response');
    div.classList.add('text');
    div.id = item.id;
    div.style.left = item.pos.x;
    div.style.top = item.pos.y;
    div.style.width = (img.width / 2) + 'px';
    div.appendChild(img);
    fragment.appendChild(div);
    texts.push(div);
  });
  container.appendChild(fragment);
  texts.map((div, index) => {
    Transform(div, true);
    div.scaleX = 0;
    div.scaleY = 0;
    switch (index) {
      case 0:
      case 2:
        div.translateY = -500;
        break;
      case 1:
        div.scaleY = 0;
        break;
      case 3:
        div.translateX = 300;
        break;
      case 4:
        div.scaleX = 0;
        div.scaleY = 0;
        break;
      case 5:
        div.translateX = 300;
        break;
      case 6:
        div.rotateX = 70;
        break;
      case 7:
        div.scaleX = 50;
        div.scaleY = 50;
        div.style.opacity = 0;
        break;
      case 8:
        div.translateY = 400;
        break;
    }
    let divTween = createjs.Tween.get(div);
    divTween
        .wait(index * 500)
        .set({opacity: 1}, div.style)
        .to({
          translateX: 0,
          translateY: 0,
          rotateX: 0,
          scaleX: 1,
          scaleY: 1
        }, 500)
        .call(() => {
          createjs.Sound.play("textComeOut", {volume: 0.5});
          if (index === texts.length - 1) {
            setTimeout(crackTween, 600);
          }
        });
  });
}

function showScene4() {
  $('#stage4').fadeIn().removeClass('hide');
  $('#stage3').fadeOut().addClass('hide');
  let s4t1 = document.getElementById('s4t1');
  let s4t2 = document.getElementById('s4t2');
  let planeBox = document.getElementById('s4planeBox');
  let plane = document.getElementById('s4plane');
  let hand = document.getElementById('s4hand');
  let tail = document.getElementById('s4tail');
  Transform(s4t1);
  Transform(s4t2);
  Transform(plane);
  Transform(hand);
  Transform(tail);
  s4t1.translateX = -400;
  s4t2.translateX = 400;
  plane.translateX = -400;
  tail.translateX = -600;
  hand.style.opacity = 0;
  createjs.Tween.get(s4t1)
      .call(() => {
        createjs.Sound.play("textComeOut", {volume: 0.5});
      })
      .to({
        translateX: 0
      }, 300, createjs.Ease.quadIn);
  createjs.Tween.get(s4t2)
      .wait(200)
      .call(() => {
        createjs.Sound.play("textComeOut", {volume: 0.5});
      })
      .to({
        translateX: 0
      }, 300, createjs.Ease.quadIn);

  function planeBounceTween() {
    createjs.Tween.get(plane, {loop: -1})
        .to({
          translateY: -10
        }, 500)
        .to({
          translateY: 10
        }, 1000)
        .to({
          translateY: 0
        }, 500);
  }

  function tailBounceTween() {
    createjs.Tween.get(tail, {loop: -1})
        .to({
          translateY: -10
        }, 510)
        .to({
          translateY: 10
        }, 1020)
        .to({
          translateY: 0
        }, 510);
  }

  createjs.Tween.get(plane)
      .wait(600)
      .to({
        translateX: 0
      }, 600, createjs.Ease.quadIn).call(() => {
        planeBounceTween();
        hand.style.opacity = 1;
        createjs.Tween.get(hand, {loop: -1})
            .to({
              translateX: 40
            }, 800)
            .wait(1000)
        ;
      }
  );
  createjs.Tween.get(tail)
      .wait(600)
      .to({
        translateX: 0
      }, 700, createjs.Ease.quadIn).call(tailBounceTween);
  let start;
  let end;
  planeBox.addEventListener('touchstart', (e) => {
    start = e.touches[0].pageX;
  });
  planeBox.addEventListener('touchmove', (e) => {
    end = e.touches[0].pageX;
  });
  planeBox.addEventListener('touchend', () => {
    if (end - start > 20) {
      createjs.Tween.get(plane)
          .call(() => {
            createjs.Sound.play("fly", {volume: 0.5});
          })
          .to({
            translateX: 100,
            translateY: 15
          }, 300)
          .call(() => {
            plane.style.opacity = 0;
            showMap();
          });
      createjs.Tween.get(tail)
          .to({
            translateX: 100,
            translateY: 15
          }, 300)
          .call(() => {
            tail.style.opacity = 0;
          });
    }
  });
  let scene4 = document.getElementById('scene4');
  let w = scene4.offsetWidth;

  function showMap() {
    Transform(scene4);
    createjs.Tween.get(scene4).to({translateX: -w / 2}, 0).call(fly);
  }

  function fly() {
    let s4map = document.getElementById('s4map');
    let s4planeIcon = document.getElementById('s4planeIcon');
    Transform(s4planeIcon);
    Transform(s4map);
    let starX = s4planeIcon.offsetLeft;
    let starY = s4planeIcon.offsetTop;
    let desX = s4map.offsetWidth * 0.815;
    let desY = s4map.offsetHeight * 0.65;
    createjs.Tween.get(s4planeIcon, {onChange: handleFly})
        .to({
          translateX: desX - starX - 40,
          translateY: desY - starY
        }, 3000)
        .wait(100)
        .call(() => {
          $('#s4path').addClass('show');
        })
        .wait(3000)
        .call(showScene5);

    function handleFly(e) {
      createjs.Tween.get(s4map).to({translateX: starX - desX}, 3000);
    }
  }
}

function showScene5() {
  $('#stage4').fadeOut().addClass('hide');
  $('#stage5').fadeIn().removeClass('hide');
  $('#s5btn').click(() => {
    showScene6();
  });
}

function showScene6() {
  $('#stage5').fadeOut().addClass('hide');
  $('#stage6').fadeIn().removeClass('hide');
  let currentMap = 1;
  let music;
  let s6scroll;
  let s6scrollW;

  // 显示地图
  function showMap(n) {
    if (music) {
      music.stop();
      music = null;
    }
    let map;
    let scrollElement;
    let mapElement;
    let text = '';
    if (n === 1) {
      currentMap = 1;
      music = createjs.Sound.play("reef", {loop: -1, volume: 0.5});
      map = loadingAssetsQueue.getResult('s6map1');
      scrollElement = document.getElementById('s6Map1Scroll');
      mapElement = $('#s6map1');
      text = '与海龟共享水趣';
    } else {
      currentMap = 2;
      music = createjs.Sound.play("forest", {loop: -1, volume: 0.5});
      map = loadingAssetsQueue.getResult('s6map2');
      scrollElement = document.getElementById('s6Map2Scroll');
      mapElement = $('#s6map2');
      text = '穿梭于热带雨林';
    }

    // $('#s6text').text(text);
    s6scrollW = Math.floor(window.innerHeight / map.height * map.width);
    let scrollStartX = s6scrollW / 2 - window.innerWidth / 2;
    mapElement.width(s6scrollW);
    s6scroll = new IScroll(scrollElement, {
      mouseWheel: true,
      startX: -scrollStartX,
      scrollX: true,
      scrollY: false,
      scrollbars: false,
      bounce: false,
      tap: true,
      deceleration: 0.01
    });
    // dot点击事件
    $('#s6turtle').on('tap click', () => {
      createjs.Sound.play("click", {volume: 0.5});
      // $('.s6text1').show();
    });
    $('#s6Map2Dot2').on('tap click', () => {
      createjs.Sound.play("click", {volume: 0.5});
      // $('.s6text2').show();
    });
    $('#s6nav').on('tap click', () => {
      createjs.Sound.play("click", {volume: 0.5});
      if (currentMap === 1) {
        $('#s6Map1Scroll').hide();
        $('#s6Map2Scroll').show();
        showMap(2);
        currentMap = 2;
      } else {
        switchScene($('#stage6'), $('#stage7'));
        showScene7();
        if (music) {
          music.stop();
          music = null;
        }
        if(s6scroll) {
          s6scroll.destroy();
          s6scroll = null;
        }
      }
    });
  }

  showMap(1);
  // 手机左右转动
  let timefragment = 0;
  let nowts = 0;
  if (window.DeviceOrientationEvent) {
    window.addEventListener('deviceorientation', orientationHandler, false);
  }

  function orientationHandler(e) {
    nowts = new Date().getTime();
    if (nowts - timefragment > 37) {
      timefragment = nowts;
      let left = e.gamma / 90 * 30;
      if (Math.abs(left) > 4) {
        scroll(left);
      }
    }

    function scroll(x) {
      if (s6scroll.x + x > 0 || s6scroll.x + x < -s6scrollW + window.innerWidth) {
        x = 0;
      }
      s6scroll.scrollBy(x, 0);
    }
  }
}

function showScene7() {
  // bgSound.stop();
  // bgSound = null;
  createjs.Sound.play("videoBg", {loop: -1, volume: 0.5});
  let videoHeight = Math.ceil(window.innerWidth / 1920 * 1080);

  function addVideoH5() {
    document.getElementById('video').play();
    $('#video').width('100%');
    $('#video').height(videoHeight);
  }

  function addVideo() {
    let iframe = $('<iframe src="http://v.qq.com/iframe/player.html?vid=m0507koncvm&tiny=0&auto=1" frameborder=0></iframe>');
    iframe.width(window.innerWidth);
    iframe.height(videoHeight);
    $('#scene7').prepend(iframe);
  }

  // addVideoH5();
  addVideo();
  $('#s7bottom').css('top', videoHeight);
  $('#s7btn1').on('click tap', () => {
    $('#s7share').removeClass('hide');
  });
  $('#s7share').on('click tap', () => {
    $('#s7share').addClass('hide');
  });
  var count = 0;
  $('#s7btns').css({transform: 'translateX(' + window.innerWidth +'px)'});
  $("#swiper").slidesjs({
    width: window.innerWidth,
    height: window.innerHeight - videoHeight,
    navigation: {
      active: false,
      // [boolean] Generates next and previous buttons.
      // You can set to false and use your own buttons.
      // User defined buttons must have the following:
      // previous button: class="slidesjs-previous slidesjs-navigation"
      // next button: class="slidesjs-next slidesjs-navigation"
      effect: "slide"
    },
    pagination: {
      active: false,
      // [boolean] Create pagination items.
      // You cannot use your own pagination. Sorry.
      effect: "slide"
      // [string] Can be either "slide" or "fade".
    },
    play: {
      auto: true,
      interval: 3000
    },
    callback: {
      start: function(number) {
        $('#s7bar' + number).show().siblings('.s7bar').hide();
        if(count === 2) {
          var w = $('#slogans').width();
          $('#slogans').css({transform: 'translateX(-' + window.innerWidth + w +'px)'});
          $('#s7btns').css({
            transform: 'translateX(0)',
            transition: 'transform 0.2s linear'
          });
        }
      },
      complete: function (number) {
        count += number;
      }
    }
  });
}

function showScene8() {
  $('#s7share').addClass('hide');
  switchScene($('#stage7'), $('#stage8'));
}